import { createStore } from 'vuex'
import axios from 'axios'

// API基础URL
const API_URL = 'http://localhost:8000/api/v1'

export default createStore({
  state: {
    categories: [],
    tools: [],
    currentTool: null,
    toolsByCategory: [],
    userSubscriptions: [],
    loading: false,
    error: null
  },
  
  getters: {
    getToolById: (state) => (id) => {
      return state.tools.find(tool => tool.id === parseInt(id))
    },
    
    getToolsByCategory: (state) => (categoryId) => {
      if (!categoryId) return state.tools
      return state.tools.filter(tool => tool.category_id === parseInt(categoryId))
    },
    
    isToolSubscribed: (state) => (toolId, userId) => {
      return state.userSubscriptions.some(
        sub => sub.tool_id === parseInt(toolId) && 
               sub.user_id === parseInt(userId) && 
               sub.is_active
      )
    }
  },
  
  mutations: {
    setCategories(state, categories) {
      state.categories = categories
    },
    
    setTools(state, tools) {
      state.tools = tools
    },
    
    setCurrentTool(state, tool) {
      state.currentTool = tool
    },
    
    setToolsByCategory(state, toolsByCategory) {
      state.toolsByCategory = toolsByCategory
    },
    
    setUserSubscriptions(state, subscriptions) {
      state.userSubscriptions = subscriptions
    },
    
    addUserSubscription(state, subscription) {
      state.userSubscriptions.push(subscription)
    },
    
    removeUserSubscription(state, { userId, toolId }) {
      const index = state.userSubscriptions.findIndex(
        sub => sub.user_id === userId && sub.tool_id === toolId
      )
      if (index !== -1) {
        state.userSubscriptions.splice(index, 1)
      }
    },
    
    setLoading(state, isLoading) {
      state.loading = isLoading
    },
    
    setError(state, error) {
      state.error = error
    },
    
    updateCurrentToolParams(state, parametersSchema) {
      if (state.currentTool) {
        state.currentTool.parameters_schema = parametersSchema
      }
    }
  },
  
  actions: {
    async fetchCategories({ commit }) {
      try {
        commit('setLoading', true)
        const response = await axios.get(`${API_URL}/categories`)
        commit('setCategories', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to fetch categories')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async fetchTools({ commit }) {
      try {
        commit('setLoading', true)
        const response = await axios.get(`${API_URL}/tools`)
        commit('setTools', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to fetch tools')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async fetchToolsByCategory({ commit }) {
      try {
        commit('setLoading', true)
        const response = await axios.get(`${API_URL}/tools/by-category`)
        commit('setToolsByCategory', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to fetch tools by category')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async fetchTool({ commit }, toolId) {
      try {
        commit('setLoading', true)
        const response = await axios.get(`${API_URL}/tools/${toolId}`)
        commit('setCurrentTool', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to fetch tool')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async fetchToolParams({ commit }, toolId) {
      try {
        commit('setLoading', true)
        const response = await axios.get(`${API_URL}/tools/${toolId}/params`)
        
        if (response.data && response.data.parameters_schema) {
          commit('updateCurrentToolParams', response.data.parameters_schema)
        }
        
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to fetch tool parameters')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async runTool({ commit }, { toolId, parameters }) {
      try {
        commit('setLoading', true)
        const response = await axios.post(`${API_URL}/tools/${toolId}/run`, {
          parameters
        })
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to run tool')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async fetchUserSubscriptions({ commit }, userId) {
      try {
        commit('setLoading', true)
        const response = await axios.get(`${API_URL}/subscriptions?user_id=${userId}`)
        commit('setUserSubscriptions', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to fetch user subscriptions')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async subscribeToTool({ commit }, { userId, toolId }) {
      try {
        commit('setLoading', true)
        const response = await axios.post(`${API_URL}/subscriptions/user/${userId}/tool/${toolId}`)
        commit('addUserSubscription', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message || 'Failed to subscribe to tool')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async unsubscribeFromTool({ commit }, { userId, toolId }) {
      try {
        commit('setLoading', true)
        await axios.delete(`${API_URL}/subscriptions/user/${userId}/tool/${toolId}`)
        commit('removeUserSubscription', { userId, toolId })
      } catch (error) {
        commit('setError', error.message || 'Failed to unsubscribe from tool')
        throw error
      } finally {
        commit('setLoading', false)
      }
    },
    
    async createTool({ commit, dispatch }, toolData) {
      try {
        commit('setLoading', true)
        console.log('Creating tool with data:', toolData)
        const response = await axios.post(`${API_URL}/tools`, toolData)
        
        await dispatch('fetchTools')
        
        return response.data
      } catch (error) {
        console.error('Error creating tool:', error, error.response?.data)
        commit('setError', error.message || 'Failed to create tool')
        throw error
      } finally {
        commit('setLoading', false)
      }
    }
  }
}) 